'use strict';

exports.main = async (event, context) => {
  console.log('消息推送云函数被调用，参数:', event)
  
  const { type, userId, title, content, data = {}, pushMethods = ['database'] } = event
  
  if (!userId || !title || !content) {
    return { code: 400, msg: '参数不完整' }
  }

  const db = uniCloud.database()
  const results = {
    database: { success: false, error: null },
    uniPush: { success: false, error: null },
    wechat: { success: false, error: null },
    sms: { success: false, error: null }
  }
  
  try {
    // 1. 数据库消息存储到 chatMessages 表（必须）
    if (pushMethods.includes('database')) {
      try {
        // 构建符合 chatMessages.schema.json 的消息记录
        const chatMessage = {
          taskId: data.taskId || 'system', // 关联的任务ID
          type: 'system', // 消息类型：系统消息
          senderId: 'admin', // 发送者：管理员
          senderAvatar: '', // 管理员头像（可选）
          senderNickname: '系统管理员', // 发送者昵称
          receiverId: userId, // 接收者用户ID
          receiverAvatar: '', // 接收者头像（稍后可以查询用户信息补充）
          receiverNickname: '', // 接收者昵称（稍后可以查询用户信息补充）
          content: content, // 消息内容
          createTime: new Date(), // 创建时间
          status: 'sent', // 消息状态
          title: title // 消息标题
        }
        
        // 尝试获取接收者的用户信息来补充头像和昵称
        try {
          const receiverInfo = await db.collection('uni-id-users')
            .where({ _id: userId })
            .field({ nickname: true, avatar: true })
            .get()
          
          if (receiverInfo.data && receiverInfo.data.length > 0) {
            const user = receiverInfo.data[0]
            chatMessage.receiverAvatar = user.avatar || ''
            chatMessage.receiverNickname = user.nickname || '用户'
          }
        } catch (userError) {
          console.log('获取用户信息失败，使用默认值:', userError)
          chatMessage.receiverNickname = '用户'
        }
        
        // 保存到 chatMessages 表
        await db.collection('chatMessages').add(chatMessage)
        results.database.success = true
        console.log('消息已保存到 chatMessages 表')
        
        // 同时保存到 user_messages 表作为备份（兼容原有逻辑）
        const userMessageRecord = {
          user_id: userId,
          type: type || 'system',
          title: title,
          content: content,
          data: data,
          is_read: false,
          create_time: new Date(),
          update_time: new Date()
        }
        
        try {
          await db.collection('user_messages').add(userMessageRecord)
          console.log('消息也已保存到 user_messages 表')
        } catch (backupError) {
          console.log('备份到 user_messages 表失败:', backupError)
          // 不影响主流程
        }
        
      } catch (error) {
        results.database.error = error.message
        console.error('数据库消息保存失败:', error)
      }
    }
    
    // 2. uni-push 实时推送
    if (pushMethods.includes('uniPush')) {
      try {
        await sendUniPushMessage(userId, title, content, data)
        results.uniPush.success = true
      } catch (error) {
        results.uniPush.error = error.message
        console.error('uni-push推送失败:', error)
      }
    }
    
    // 3. 微信小程序订阅消息
    if (pushMethods.includes('wechat')) {
      try {
        await sendWechatMessage(userId, title, content, data)
        results.wechat.success = true
      } catch (error) {
        results.wechat.error = error.message
        console.error('微信推送失败:', error)
      }
    }
    
    // 4. 短信通知
    if (pushMethods.includes('sms')) {
      try {
        await sendSMSMessage(userId, title, content, data)
        results.sms.success = true
      } catch (error) {
        results.sms.error = error.message
        console.error('短信推送失败:', error)
      }
    }
    
    return {
      code: 200,
      msg: '推送完成',
      data: {
        results: results,
        summary: {
          total: pushMethods.length,
          success: Object.values(results).filter(r => r.success).length,
          failed: Object.values(results).filter(r => !r.success).length
        }
      }
    }
    
  } catch (error) {
    console.error('消息推送失败:', error)
    return {
      code: 500,
      msg: '推送失败: ' + error.message,
      data: { results: results }
    }
  }
}

// uni-push 推送
async function sendUniPushMessage(userId, title, content, data) {
  // 需要先配置 uni-push 服务
  console.log('uni-push推送 - 用户:', userId, '标题:', title)
  
  // 示例代码（需要实际配置）
  /*
  const uniPush = uniCloud.getPushManager({
    appId: process.env.UNI_APP_ID
  })
  
  // 获取用户的推送标识
  const db = uniCloud.database()
  const userPushInfo = await db.collection('user_push_info')
    .where({ user_id: userId })
    .get()
  
  if (userPushInfo.data && userPushInfo.data.length > 0) {
    const pushInfo = userPushInfo.data[0]
    
    await uniPush.sendMessage({
      push_clientid: pushInfo.client_id,
      title: title,
      content: content,
      payload: {
        type: data.type || 'system',
        taskId: data.taskId,
        url: data.url
      }
    })
  }
  */
  
  // 模拟推送成功
  console.log('uni-push推送模拟成功')
}

// 微信小程序订阅消息
async function sendWechatMessage(userId, title, content, data) {
  console.log('微信订阅消息 - 用户:', userId, '标题:', title)
  
  // 示例代码（需要微信小程序订阅消息模板）
  /*
  const db = uniCloud.database()
  
  // 获取用户的微信openid
  const userInfo = await db.collection('uni-id-users')
    .where({ _id: userId })
    .get()
  
  if (userInfo.data && userInfo.data.length > 0) {
    const user = userInfo.data[0]
    const openid = user.wx_openid && user.wx_openid.mp
    
    if (openid) {
      // 构建订阅消息
      const templateMessage = {
        touser: openid,
        template_id: process.env.WECHAT_TEMPLATE_ID,
        page: data.url || 'pages/message/index',
        data: {
          thing1: { value: title },
          thing2: { value: content.substring(0, 20) },
          time3: { value: new Date().toLocaleString() }
        }
      }
      
      // 调用微信API
      const result = await uniCloud.httpclient.request({
        method: 'POST',
        url: `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${await getWechatAccessToken()}`,
        data: templateMessage,
        dataType: 'json'
      })
      
      if (result.data.errcode !== 0) {
        throw new Error(`微信推送失败: ${result.data.errmsg}`)
      }
    }
  }
  */
  
  // 模拟推送成功
  console.log('微信订阅消息模拟成功')
}

// 短信通知
async function sendSMSMessage(userId, title, content, data) {
  console.log('短信通知 - 用户:', userId, '标题:', title)
  
  // 示例代码（需要配置短信服务商）
  /*
  const db = uniCloud.database()
  
  // 获取用户手机号
  const userInfo = await db.collection('uni-id-users')
    .where({ _id: userId })
    .get()
  
  if (userInfo.data && userInfo.data.length > 0) {
    const user = userInfo.data[0]
    const mobile = user.mobile
    
    if (mobile) {
      // 调用短信服务商API
      const smsContent = `【校园互助+】${title}：${content.substring(0, 50)}...`
      
      const result = await uniCloud.httpclient.request({
        method: 'POST',
        url: 'https://sms-api.example.com/send',
        data: {
          mobile: mobile,
          content: smsContent,
          sign: '校园互助+'
        },
        headers: {
          'Authorization': `Bearer ${process.env.SMS_API_KEY}`
        },
        dataType: 'json'
      })
      
      if (result.data.code !== 0) {
        throw new Error(`短信发送失败: ${result.data.message}`)
      }
    }
  }
  */
  
  // 模拟推送成功
  console.log('短信通知模拟成功')
}

// 获取微信access_token（示例）
async function getWechatAccessToken() {
  // 这里应该实现微信access_token的获取和缓存逻辑
  return 'mock_access_token'
}
